<?php

namespace app\admin\model\user;

use app\common\model\Setting as SettingModel;
use think\Model;

/**
 * 分销商资金明细模型
 * Class Apply
 * @package app\common\model\dealer
 */
class Capital extends Model
{
    protected $name = 'dealer_capital';



    public function user(){
        return $this->belongsTo("app\common\model\User",'user_id','user_id');
    }


    public function wxapp(){
        return $this->belongsTo("app\common\model\Wxapp",'wxapp_id','wxapp_id');
    }

    /**
     * 从缓存中获取商城名称
     * @param $data
     * @return array
     */
    public function getStoreName($data)
    {
        $names = [];
        foreach ($data as $wxapp) {
            $names[$wxapp['wxapp_id']] = SettingModel::getItem('store', $wxapp['wxapp_id'])['name'];
        }
        return $names;
    }


    public function getList($query = []){
        // 设置查询条件
        !empty($query) && $this->setQueryWhere($query);

        // 获取列表数据
        return $this->alias('capital')
            ->field('capital.*')
            ->join('wxapp', 'wxapp.wxapp_id = capital.wxapp_id')
            ->join('user', 'user.user_id = capital.user_id')
            ->order(['capital.create_time' => 'desc'])
            ->paginate(15, false, [
                'query' => request()->request()
            ]);
    }


    /**
     * 设置查询条件
     * @param $query
     */
    private function setQueryWhere($query)
    {
        // 设置默认的检索数据
        $params = $this->setQueryDefaultValue($query, [
            'user_id' => 0,

        ]);
        // 用户ID
          $params['user_id'] > 0 && $this->where('capital.user_id', '=', $params['user_id']);
        // 用户昵称/订单号

        if (isset($query['search']) && !empty($query['search'])) {
            $this->where('wxapp.wxapp_name|user.nickName', 'like', '%' . trim($query['search']) . '%');
        }

        // 起始时间
        !empty($params['start_time']) && $this->where('capital.create_time', '>=', strtotime($params['start_time']));
        // 截止时间
        !empty($params['end_time']) && $this->where('capital.create_time', '<', strtotime($params['end_time']) + 86400);
    }

    /**
     * 设置默认的检索数据
     * @param $query
     * @param array $default
     * @return array
     */
    protected function setQueryDefaultValue(&$query, $default = [])
    {
        $data = array_merge($default, $query);
        foreach ($query as $key => $val) {
            if (empty($val) && isset($default[$key])) {
                $data[$key] = $default[$key];
            }
        }
        return $data;
    }
}